package com.coolweather.android;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;

import com.coolweather.android.gson.Weather;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherActivity extends Activity {

    private String mWeatherId;
    private Weather weatherObj;
    private TextView txtCity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather1);
        String weatherString="";
        txtCity = findViewById(R.id.textView);
        mWeatherId = getIntent().getStringExtra("weather_id");
        //Log.d("weather",mWeatherId);
        String address="http://guolin.tech/api/weather?cityid="+mWeatherId+"&key=bc0418b57b2d4918819d3974ac1285d9";
        //Log.d("address",address);
        //queryDataFromServer(address);

        SharedPreferences prefs = PreferenceManager.
                getDefaultSharedPreferences(WeatherActivity.this);
        weatherString = prefs.getString("weather",null);
        Log.d("SharedPreferences",weatherString);
        if (weatherString.equals("")){
            queryDataFromServer(address);
        }
        else {
            try {
                dispWeather(weatherString);
                txtCity.setText(weatherObj.basic.cityName);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



    }

    private void dispWeather(String weatherString) throws JSONException {
        parseWeatherData(weatherString);
    }

    private void queryDataFromServer(final String address){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(address).build();
                    Response response = null;
                    response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d("responseData", responseData);
                    //parseWeatherData(responseData);
                    SharedPreferences.Editor editor = PreferenceManager.
                            getDefaultSharedPreferences(WeatherActivity.this).edit();
                    editor.putString("weather",responseData);
                    editor.apply();

                    SharedPreferences prefs = PreferenceManager.
                            getDefaultSharedPreferences(WeatherActivity.this);
                    String weatherString = prefs.getString("weather",null);
                    Log.d("SharedPreferences",weatherString);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseWeatherData(String responseData) throws JSONException{
        JSONObject firstLevel = new JSONObject(responseData);
        JSONArray jsonArray = firstLevel.getJSONArray("HeWeather");
        String weatherContent = jsonArray.getJSONObject(0).toString();
        Log.d("parseWeatherData",weatherContent);
        weatherObj = new Gson().fromJson(weatherContent,Weather.class);
        Log.d("parseWeatherData",weatherObj.basic.cityName);

    }




//    private ScrollView weatherLayout;
//    private String mWeatherId;
//    private TextView txtCity,titleCity,titleUpdateTime,degreeText,weatherInfoText,aqiText,pm25Text,comfortText,carWashText,sportText;
//    private LinearLayout forecastLayout;
//    public SwipeRefreshLayout swipeRefresh;
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_weather);
//        titleCity = (TextView) findViewById(R.id.title_city);
//        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
//        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
//        degreeText = (TextView) findViewById(R.id.degree_text);
//        weatherInfoText = (TextView) findViewById(R.id.wether_info_text);
//        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
//        aqiText = (TextView) findViewById(R.id.aqi_text);
//        pm25Text = (TextView) findViewById(R.id.pm25_text);
//        comfortText =(TextView) findViewById(R.id.comfort_text);
//        carWashText = (TextView) findViewById(R.id.car_wash_text);
//        sportText = (TextView) findViewById(R.id.sport_text);
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//        String wetherString = prefs.getString("wether",null);
//        if (wetherString != null){
//            Weather weather = handleWeatherResponse(wetherString);
//            showWeatherInfo(weatherId);
//
//        }else {
//            String weatherId = getIntent().getStringExtra("weather_id");
//            weatherLayout.setVisibility(View.INVISIBLE);
//            requestWeather(weatherId);
//
//        }
//
//
//
////        mWeatherId = getIntent().getStringExtra("weather_id");
////        txtCity = (TextView) findViewById(R.id.textView);
//        //swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
//        //swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
//
//        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                requestWeather(mWeatherId);
//                swipeRefresh.setRefreshing(false);
//
//            }
//        });
//    }
//
//    //private void dispWeather(Weather weather)  { txtCity.setText(weather.basic.cityName); }
//
//    public void requestWeather(final String weatherId) {
//        String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
//        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                final String responseText = response.body().string();
//                Log.d("info",responseText);
//                 Weather weather = null;
//                try {
//                    weather= parseWeatherData(responseText);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                final Weather finalWeather = weather;
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
//                        editor.putString("weather", responseText);
//                        editor.apply();
//                        //dispWeather(finalWeather);
//                    }
//                });
//            }
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
//                        swipeRefresh.setRefreshing(false);
//                    }
//                });
//            }
//        });
//
//    }
//
//
////    private Weather parseWeatherData(String responseData) throws JSONException {
////        JSONObject fristLevel = new JSONObject(responseData);
////        JSONArray jsonArray = fristLevel.getJSONArray("HeWeather");
////        String weatherContent = jsonArray.getJSONObject(0).toString();
////        Log.d("parseWeatherData", weatherContent);
////        return new Gson().fromJson(weatherContent, Weather.class);
////    }
//
//
//     public static Weather handleWeatherResponse(String response) {
//        try{
//            JSONObject jsonObject = new JSONObject(response);
//            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather");
//            String weatherContent = jsonArray.getJSONObject(0).toString();
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        return null;
//     }
}
    

